<%@ page import="net.cyue.homework.student.management.util.DB" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.util.List" %>
<%@ page import="net.cyue.homework.student.management.entity.Major" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    // 不处理异常
    // 分页查询 major
    int pageSize = 5;
    int selectPage = 1;
    String selectPageString =  request.getParameter("page");
    if (selectPageString != null && !selectPageString.isEmpty()) {
        selectPage = Integer.parseInt(selectPageString);
    }

    // 查询总数
    int majorCount = 0;
    int pageCount = 0;
    ResultSet countResultSet = DB.POOL.query("select count(1) from major");
    countResultSet.next();
    majorCount = countResultSet.getInt(1);
    pageCount = (int) Math.ceil((double) majorCount / pageSize);
    countResultSet.close();
    // 超出范围
    if (selectPage < 1 || selectPage > pageCount) {
        response.sendRedirect("./admin_major.jsp");
    }

    int pageStartOffset = (selectPage - 1) * pageSize;
    List<Major> majorList = new ArrayList<>();
    ResultSet majorResult = DB.POOL.query("select * from major limit " + pageStartOffset + ", " + pageSize);
    while (majorResult.next()) {
        int id = majorResult.getInt("id");
        String name = majorResult.getString("name");
        majorList.add(new Major(id, name));
    }

%>

<html>
<head>
    <meta charset="UTF-8">
    <title>洪炜斐——学生管理系统——专业管理</title>
    <link rel="stylesheet" href="./css/common.css">
    <link rel="stylesheet" href="./css/style.css">
    <link rel="stylesheet" href="./css/hf.css">
    <link rel="stylesheet" href="./css/table.css">
    <link rel="stylesheet" href="./css/custom.css">

    <style>
        main {
            padding-bottom: 5em;
        }
    </style>
</head>
<body>

    <!-- 添加专业 dialog -->
    <dialog id="dialog-major-add">
        <div class="text-center">
            <h3 style="margin: 0 0 1em;">添加专业</h3>
        </div>
        <form id="form-major-add" class="form gap-1em">
            <div class="form-item">
                <label>
                    专业名称
                </label>
                <input type="text" name="name" placeholder="请输入专业名称" required>
                <span></span>
            </div>
            <div class="flex-row justify-center gap-1em">
                <input class="button primary" type="submit" value="确定">
                <input class="button" type="reset" value="取消" onclick="closeAddMajor()">
            </div>
        </form>
    </dialog>
    <!-- 更新专业信息 dialog -->
    <dialog id="dialog-major-update">
        <div class="text-center">
            <h3 style="margin: 0 0 1em;">修改专业</h3>
        </div>
        <form id="form-major-update" class="form gap-1em">
            <div class="form-item">
                <label>
                    专业名称
                </label>
                <input type="text" name="name" placeholder="请输入专业名称" required>
                <span></span>
            </div>
            <div class="flex-row justify-center gap-1em">
                <input class="button primary" type="submit" value="确定">
                <input class="button" type="reset" value="取消" onclick="closeUpdateMajor()">
            </div>
        </form>
    </dialog>


    <jsp:include page="./component/header.jsp">
    	<jsp:param name="page" value="专业管理"/>
    </jsp:include>
    <main>
        <div class="panel items-center">
            <h2>学生专业管理</h2>
            <div class="flex-column gap-1em">
                <!-- 增加 -->
                <div class="flex-row width-100">
                    <button class="button primary" onclick="openAddMajor()">添加专业</button>
                </div>
                <!-- 数据展示 -->
                <div>
                    <table style="min-width: 40rem;">
                        <thead>
                        <tr>
                            <th>专业ID</th>
                            <th>专业名称</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        <%
                            for(Major major : majorList) {
                        %>
                        <tr>
                            <td><%= major.getId() %></td>
                            <td><%= major.getName() %></td>
                            <td>
                                <button
                                    class="button primary"
                                    onclick="openUpdateMajor(<%= major.getId() %>)"
                                >
                                    修改
                                </button>
                                <button
                                    class="button danger"
                                    onclick="deleteMajor(<%= major.getId() %>)"
                                >
                                    删除
                                </button>
                            </td>
                        </tr>
                        <% } %>
                        </tbody>
                    </table>
                    <div>
                        <p>
                            总共有<span><%= majorCount %></span>条数据
                        </p>
                        <p>
                            总共有<span><%= pageCount %></span>页
                        </p>
                    </div>
                    <!-- 切换显示页数 -->
                    <div>
                        <ul class="flex-row justify-center">
                            <li>
                                <a href="javascript: changePage(1)">首页</a>
                            </li>
                            <li>
                                <a href="javascript: changePage(<%= selectPage %> - 1)">上一页</a>
                            </li>
                            <li>
                                <a href="javascript: changePage(<%= selectPage %> + 1)">下一页</a>
                            </li>
                            <li>
                                <a href="javascript: changePage(<%= pageCount %>)">尾页</a>
                            </li>
                            <li>
                                第<span><%= selectPage %></span>/<span><%= pageCount %></span>页
                            </li>
                        </ul>
                    </div>

                </div>
            </div>
        </div>
    </main>

    <script>
        function changePage(page) {
            if (page < 1 || page > <%= pageCount %>) {
                alert("页数超出范围");
                return;
            }
            const query = window.location.search.substring(1);
            const params = query.split("&");
            const map = new Map();
            for (let i = 0; i < params.length; i++) {
                const param = params[i].split("=");
                map.set(param[0], param[1]);
            }
            map.set("page", page);
            // [key, value]
            // [["page", "1"], ["major", "1"]]
            // [“page”, "1"].join("=") => "page=1"
            // ["page=1", "major=1"]
            // "page=1&major=1"
            window.location.href = window.location.pathname + "?" +
                Array.from(map.entries()).map(param => param.join("=")).join("&");
        }


        let wannaUpdateMajorID = undefined;
        const addMajorDialog = document.querySelector("#dialog-major-add");
        const updateMajorDialog = document.querySelector("#dialog-major-update");
        const addMajorForm = document.querySelector("#form-major-add");
        const updateMajorForm = document.querySelector("#form-major-update");
        function openAddMajor() {
            addMajorDialog.showModal();
        }
        function closeAddMajor() {
            addMajorForm.reset();
            addMajorDialog.close();
        }
        function openUpdateMajor(id) {
            wannaUpdateMajorID = id;
            fetch("./api/major?id=" + id)
                .then(res => res.json())
                .then(result => {
                    const major = result.data;
                    updateMajorForm.id.value = major.id;
                    updateMajorForm.name.value = major.name;
                });
            updateMajorDialog.showModal();
        }
        function closeUpdateMajor() {
            updateMajorForm.reset();
            updateMajorDialog.close();
        }


        addMajorForm.onsubmit = (e) => {
            e.preventDefault();

            fetch("./api/major", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    name: addMajorForm.name.value,
                }),
            })
            .then(res => res.json())
            .then(result => {
                if (result.code !== 200) {
                    alert("添加失败");
                    return;
                }
                alert("添加成功");
                window.location.reload();
            });
        }
        updateMajorForm.onsubmit = (e) => {
            e.preventDefault();

            fetch("./api/major", {
                method: "PUT",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    id: wannaUpdateMajorID,
                    name: updateMajorForm.name.value,
                }),
            })
            .then(res => res.json())
            .then(result => {
                if (result.code !== 200) {
                    alert("更新失败");
                    return;
                }
                alert("更新成功");
                window.location.reload();
            });
        }

        function deleteMajor(id) {
            if (!window.confirm("是否删除")) {
                return;
            }
            console.log("删除学生" + id);
            fetch("./api/major", {
                method: "DELETE",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    id
                })
            })
            .then(res => res.json())
            .then(result => {
                if (result.code !== 200) {
                    alert("删除失败");
                    return;
                }
                alert("删除成功");
                window.location.reload();
            });
        }
    </script>
</body>
</html>

